from ninja import Router

from apps.manager.user_manager.serializers import ApiSerializer
from apps.schemas import R
from models.models import Api
from utils.auth import ManagerAuthBearer
from utils.decorators import handle_exception

api_router = Router(tags=["接口管理"], auth=ManagerAuthBearer())


@api_router.get("/apis", summary="获取所有API")
@handle_exception("获取所有API失败")
def get_apis(request):
    apis = Api.objects.filter(user_default=0)
    groups = [api.group for api in apis]
    no_repeat_groups = list(set(groups))
    no_repeat_groups.sort(key=groups.index)
    ret = []
    for name in no_repeat_groups:
        queryset = apis.filter(group=name)
        serializer = ApiSerializer(queryset, many=True)
        ret.append({
            'group': name,
            'data': serializer.data
        })
    return R.ok(ret)